<template>
  <div>
    <el-dialog v-el-drag-dialog width="800px" :title="formName" :visible="show" @update:visible="updateShow" destroy-on-close v-if="show">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="130px">
        <el-form-item label="身份名称：" prop="RoleName">
          <el-input v-model="form.RoleName" style="width: 500px" />
        </el-form-item>
        <el-form-item label="身份等级金额：" prop="PayAmount">
          <el-input v-model="form.PayAmount" style="width: 500px" min="0" @keyup.native="proving2($event)" type="number">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="活动价：" prop="Discount">
          <el-input v-model="form.Discount" style="width: 500px" min="0" @keyup.native="proving2($event)" type="number">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="年费返还方案：" prop="TechSettingId">
          <el-select v-model="form.TechSettingId" class="flex-1" filterable placeholder="请选择" style="width: 500px">
            <el-option v-for="item in SettingOptions" :key="item.Id" :label="item.Sname" :value="item.Id" style="width: 500px">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="标识图标：" prop="SignIcon">
          <div class="flex">
            <el-input v-model="form.SignIcon" style="width: 360px" disabled />
            <el-popover placement="bottom" style="width: 100px" trigger="click">
              <div class="m-b-1">
                <div v-for="item of i_icon_y" :key="item.icon" class="userAvater" :class="item.icon" @click="choseIcon(item)"></div>
              </div>
              <div class="m-b-1">
                <div v-for="item of i_icon_p" :key="item.icon" class="userAvater" :class="item.icon" @click="choseIcon(item)"></div>
              </div>
              <div v-for="item of i_icon_H" :key="item.icon" class="userAvater" :class="item.icon" @click="choseIcon(item)"></div>
              <el-button slot="reference">选择</el-button>
            </el-popover>
            <div :class="form.SignIcon" style="width: 40px;background-size: contain;background-repeat: no-repeat;"></div>
          </div>
        </el-form-item>
        <el-form-item label="铭牌字体色：" prop="ColorCard">
          <div class="flex">
            <el-input v-model="form.ColorCard" style="width: 200px" />
            <div>例:#000/rgb(0,0,0)</div>
            <div class="m-l-2">预览：</div>
            <el-color-picker v-model="form.ColorCard"></el-color-picker>
            <!-- <div class="colorBox" :style="`background-color:${form.ColorCard}`"></div> -->
          </div>
        </el-form-item>
        <el-form-item label="铭牌卡片：" prop="Nameplate">
          <div class="flex">
            <img class="EquityPathImg m-r-2" v-show="form.Nameplate" :src="form.Nameplate" @click="handlePictureCardPreview(form.Nameplate)" alt="" />
            <el-upload :action="upload" :headers="headerObj" ref="uploadBox" multiple :before-upload="beforeUploadFun" :limit="1" :auto-upload="true" accept=".jpg, .jpeg, .png" :show-file-list="false" :on-success="upLoadSuccess2">
              <el-button size="small" type="primary">点击上传</el-button>
              <el-button size="small" type="warning" @click.stop="form.Nameplate = ''">移除</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传1张jpg/jpeg/png文件
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="权益介绍：" prop="EquityPath">
          <div class="flex">
            <img class="EquityPathImg m-r-2" v-show="form.EquityPath" :src="form.EquityPath" @click="handlePictureCardPreview(form.EquityPath)" alt="" />
            <el-upload :action="upload" :headers="headerObj" ref="uploadBox" multiple :before-upload="beforeUploadFun" :limit="1" :auto-upload="true" accept=".jpg, .jpeg, .png" :show-file-list="false" :on-success="upLoadSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
              <el-button size="small" type="warning" @click.stop="form.EquityPath = ''">移除</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传1张jpg/jpeg/png文件
              </div>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="备注：" prop="Remark">
          <el-input v-model="form.Remark" style="width: 500px" />
        </el-form-item>
        <el-form-item label="机构身份：" prop="Institution">
          <el-radio v-model="form.Institution" :label="true">是</el-radio>
          <el-radio v-model="form.Institution" :label="false">否</el-radio>
        </el-form-item>
        <el-form-item label="默认身份：" prop="DefaultRole">
          <el-radio v-model="form.DefaultRole" :label="true">是</el-radio>
          <el-radio v-model="form.DefaultRole" :label="false">否</el-radio>
        </el-form-item>
        <el-form-item label="系统身份：" prop="SystemRole">
          <el-radio v-model="form.SystemRole" :label="true">是</el-radio>
          <el-radio v-model="form.SystemRole" :label="false">否</el-radio>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="updateShow(false)"> 取消 </el-button>
        <el-button type="primary" @click="save"> 保存 </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible2" width="50%">
      <img style="width: 100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
  import { deepClone } from '@/utils'
  import { saveUserRole } from '@/api/system/user-role'
  import { mapState } from 'vuex'
  import { getTechCostSetting } from '@/api/system/tech-cost-setting'
  import { GetUploadToken } from '@/api/ShareSetting/poster'
  export default {
    components: {},
    props: {
      show: {
        type: Boolean,
        default() {
          return false
        }
      },
      formData: {
        type: Object,
        default() {
          return {}
        }
      }
    },
    data() {
      return {
        upload: process.env.VUE_APP_UPLOAD_API + '/api/Tools/UploadFiles',
        tips: [
          {
            name: '基础信息',
            active: false,
            icon: 'el-icon-user'
          }
        ],
        form: {
          DefaultRole: false,
          SystemRole: false,
          SignIcon: ''
        },
        formTmpl: {
          RoleName: '',
          // SignIcon: '',
          SystemRole: false,
          Remark: ''
        },
        SettingOptions: [],
        rules: {
          RoleName: [
            { required: true, message: '身份名称必填', trigger: 'blur' },
            { min: 1, max: 50, message: '身份名称长度在 1 到 50 个字符', trigger: 'blur' }
          ],
          TechSettingId: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          PayAmount: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          SignIcon: [{ required: true, message: '必填', trigger: 'blur' }],
          Discount: [
            { required: true, message: '必填', trigger: 'blur' },
          ],

        },
        i_icon_p: [
          { icon: "id_p_0" },
          { icon: "id_p_1" },
          { icon: "id_p_2" },
          { icon: "id_p_3" },
          { icon: "id_p_4" },
          { icon: "id_p_5" },
          { icon: "id_p_6" },
        ],
        i_icon_y: [
          { icon: "id_y_0" },
          { icon: "id_y_1" },
          { icon: "id_y_2" },
          { icon: "id_y_3" },
          { icon: "id_y_4" },
          { icon: "id_y_5" },
          { icon: "id_y_6" },
        ],
        i_icon_H: [],
        headerObj: {
          Authorization: ''
        },
        dialogImageUrl: "",
        dialogVisible2: false,
      }
    },
    computed: {
      formName() {
        if (this.form.Id) {
          return '编辑'
        }
        return '新增'
      },
      ...mapState({
        userId: state => state.user.id,
      }),

    },
    watch: {

      formData: {
        deep: true,
        immediate: true,
        handler(val) {
          if (this.$refs['dataForm']) {
            this.$refs['dataForm'].clearValidate()
          }
          this.form = deepClone({ ...this.formTmpl, ...val })
        }
      },

    },
    created() {
      // console.log('环境', process.env)
      if (process.env.VUE_APP_ENV == 'development' || process.env.VUE_APP_ENV == 'staging') {
        // console.log('傲世轻物群无')
        this.i_icon_H = [
          { icon: "id_vh_1" },
          { icon: "id_vh_2" },
          { icon: "id_vh_3" },
          { icon: "id_vh_4" },
        ]
      }
      this.GetUploadTokenFun()
      this.getSettingOptions()
    },
    methods: {
      handlePictureCardPreview(file) {
        //图片放大
        this.dialogImageUrl = file;
        this.dialogVisible2 = true;
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      async beforeUploadFun(e) {
        if (!this.headerObj.Authorization) {
          return false
        }

      },

      async GetUploadTokenFun() {
        let { Data } = await GetUploadToken()
        this.headerObj.Authorization = Data || ''
      },

      upLoadSuccess2(res) {
        console.log('上传结束', res)
        console.log(this.$refs.uploadBox)
        if (res.code === 0) {
          // this.form.EquityPath = res.data.fileUrl
          this.$set(this.form, 'Nameplate', res.data.fileUrl)
        } else {
          if (this.sstimer) {
            clearTimeout(this.sstimer)
          }
          this.sstimer = setTimeout(() => {
            this.$notify({
              title: '上传失败',
              message: res.msg,
              type: 'warning',
              duration: 4500
            })
          }, 800)
        }
      },
      upLoadSuccess(res) {
        console.log('上传结束', res)
        console.log(this.$refs.uploadBox)
        if (res.code === 0) {
          // this.form.EquityPath = res.data.fileUrl
          this.$set(this.form, 'EquityPath', res.data.fileUrl)
        } else {
          if (this.sstimer) {
            clearTimeout(this.sstimer)
          }
          this.sstimer = setTimeout(() => {
            this.$notify({
              title: '上传失败',
              message: res.msg,
              type: 'warning',
              duration: 4500
            })
          }, 800)
        }
      },
      getSettingOptions() {
        getTechCostSetting({ IsPaging: false }).then(res => {
          this.SettingOptions = res.data
          this.SettingOptions.unshift({ Id: "00000000-0000-0000-0000-000000000000", Sname: "无" })

        })

      },
      choseIcon(item) {
        // this.form.SignIcon = item.icon
        this.$set(this.form, 'SignIcon', item.icon)
      },
      updateShow(val) {
        this.$emit('update:show', val)
      },
      afterSave() {
        this.$notify({
          title: '操作成功',
          message: 'success',
          type: 'success',
          duration: 2000
        })
        this.updateShow(false)
        this.$emit('finish')
      },
      save() {
        this.$refs['dataForm'].validate((valid) => {
          const formData = deepClone(this.form)
          if (formData.DefaultRole || formData.SystemRole) {
            if (valid) {
              saveUserRole(formData).then(() => {
                this.afterSave()
              })
            }
            return
          }
          if (formData.TechSettingId == '00000000-0000-0000-0000-000000000000') {
            this.$notify({
              title: '提示',
              message: '请选择技术服务年费配置方案',
              type: 'warning',
              duration: 2000
            })
            return
          } else {
            if (valid) {
              saveUserRole(formData).then(() => {
                this.afterSave()
              })
            }
          }


        })
      }
    }
  }
</script>
<style scoped>
  .userAvater {
    cursor: pointer;
    width: 40px;
    height: 40px;
    border-radius: 10px;
    overflow: hidden;
    display: inline-block;
    margin-right: 10px;
  }
  .userAvater:hover {
    background-color: #d8e5f5;
  }
  .EquityPathImg {
    width: 60px;
    height: 60px;
  }
  .colorBox {
    width: 36px;
    height: 36px;
    border: 1px dotted #999;
    position: relative;
  }
</style>